package com.javastar.modules.mail.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javastar.common.enums.EmailEnum;
import com.javastar.common.exception.AssertUtil;
import com.javastar.common.exception.ErrorCode;
import com.javastar.modules.mail.entity.MailEntity;
import com.javastar.modules.mail.mapper.MailMapper;
import com.javastar.modules.mail.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

/**
 * <p>
 * 邮件模版表 服务实现类
 * </p>
 *
 * @author Java星球
 * @since 2023-07-26
 */
@Service
public class MailServiceImpl extends ServiceImpl<MailMapper, MailEntity> implements MailService {
    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 邮箱注册成功发送
     * @param userNickname
     * @param userEmail
     */
    @Override
    public void sendEmailRegisterSuccessEmail(String userNickname, String userEmail) {
        MailEntity mail = lambdaQuery().eq(MailEntity::getMailType, EmailEnum.EMAIL_REGISTER_SUCCESS_MAIL.getType()).one();
        sendEmail(userEmail, mail.getSubject(), String.format(mail.getContent(), userNickname));
    }

    private void sendEmail(String userEmail, String subject, String content) {
        try {
            // 创建一个MINE消息
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            // 谁发
            helper.setFrom(from);
            // 谁要接收
            helper.setTo(userEmail);
            // 邮件主题
            helper.setSubject(subject);
            // 邮件内容   true 表示带有附件或html
            helper.setText(content, true);
            mailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            AssertUtil.error(ErrorCode.INTERNAL_SERVER_ERROR);
        }
    }
}
